package com.hnxxxy.common.shiro;

import lombok.Setter;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @CLASSDESCRIPER:
 * @AUTHOR:suhui
 * @PHONE:13319575368
 * @EMIAL:13319575368@163.COM
 * @DATE: 2020/5/14
 * @PARAMDESCRIPER:
 * @OUTPARAMDESCRIPER:
 */
public class ShiroMatcher extends HashedCredentialsMatcher {
    @Setter
    private RedisTemplate<String,Object> redisTemplate;
    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        UsernamePasswordToken mytoken = (UsernamePasswordToken) token;
        String loginname = (String) mytoken.getPrincipal();
        Object o = redisTemplate.opsForValue().get("LoginTimes:" + loginname);
        AtomicInteger numbers=new AtomicInteger(0);
        if(!StringUtils.isEmpty(o)){
            int number=(int) o;
            numbers=new AtomicInteger(number);
            if(numbers.get()>=5){
                throw new ExcessiveAttemptsException();
            }
        }
        boolean b=super.doCredentialsMatch(token,info);
        if(!b){
            redisTemplate.opsForValue().set("LoginTimes:"+loginname,numbers.incrementAndGet(),300,TimeUnit.SECONDS);
        }else{
            redisTemplate.delete("LoginTimes:"+loginname);
        }
        return b;
    }
}
